<?php

include_once APPLICATION_DIR . "/application/model/PRODUCT.php";

class Product extends DataObjects_PRODUCT
{
	public function validateInput(){
        global $error_msg;

		$posted_file = $_FILES["IMAGE"];
		if ($error_msg->isNoError() && !empty($posted_file["name"])) {
			if ($this->ID) {
				$this->OLD_IMAGE = $this->IMAGE;
			}
            $upload = new UPLOAD();
			$new_file = $upload->doUploadImage(PRODUCT_DIR."/image/", $posted_file, '', '190', '');
			if ($new_file) {
				$this->IMAGE = $new_file;
			} else {
				$error_msg->add('_MSG_UPLOAD_FAILED');
			}
		}

		$is_validate = $error_msg->isNoError();
		$is_validate = $is_validate && Product_Info::validateInputFromProduct($this);
		$is_validate = $is_validate && Product_Image::validateInputFromProduct($this);
		$is_validate = $is_validate && Product_Download::validateInputFromProduct($this);
        return $is_validate;
    }

	public function update() {
		if (!empty($this->OLD_IMAGE) && $this->IMAGE != $this->OLD_IMAGE) {
			@unlink(PRODUCT_DIR."/image/{$this->OLD_IMAGE}");
			@unlink(PRODUCT_DIR."/image/thumb{$this->OLD_IMAGE}");
		}

		return parent::update();
	}

	public function delete() {
		$product_info = new Product_Info();
		$product_info->ID_PRODUCT = $this->ID;
		$product_info->find();
		while ($product_info->fetch()) {
			$product_info->delete();
		}

		$product_image = new Product_Image();
		$product_image->ID_PRODUCT = $this->ID;
		$product_image->find();
		while ($product_image->fetch()) {
			$product_image->delete();
		}

		$product_download = new Product_Download();
		$product_download->ID_PRODUCT = $this->ID;
		$product_download->find();
		while ($product_download->fetch()) {
			$product_download->delete();
		}

		if ($this->IMAGE) {
			@unlink(PRODUCT_DIR."/image/{$this->IMAGE}");
			@unlink(PRODUCT_DIR."/image/thumb{$this->IMAGE}");
		}

		return parent::delete();
	}

	public static function isExist($name, $id = 0) {
		$product = new Product();
		$product->NAME = $name;
		if (!empty($id)) {
			$product->whereAdd("ID <> $id");
		}
		$product->find();

		return (($product->N > 0) ? 1 : 0);
	}

	public function getDetail($id) {
		if ($this->get($id)) {
			$cat = new Category();
			$cat->get($this->ID_CATEGORY);			
			$this->CATEGORY_TITLE = $cat->TITLE;

			$this->product_infos = Product_Info::getList($this->ID);

			$this->product_downloads = Product_Download::getList($this->ID);

			$this->product_images = Product_Image::getList($this->ID);

			return true;
		} else {
			return false;
		}
	}
    
    public function getListProductByCatID($catID){
        $this->ID_CATEGORY = $catID;
        $this->DISABLED = 0;
        $this->orderBy("POS ASC");
        $this->find();
    }

	public static function updateStatus($id, $status) {
		$product = new Product();
		
		if ($product->get($id)) {
			$product->DISABLED = $status;
			if ($product->update()) {
				return 1;
			}				
		}
		return 0;
	}
}
?>
